package com.zzh.netty.nio;
/**
 * @ClassName NioServer
 * @date 2021/1/28 21:55
 * @Version 1.0
 * @Description
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *@ClassName NioServer
 *@date 2021/1/28 21:55
 *@Version 1.0
 *@Description //
 */
public class NioServer {
    static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务启动成功。。。");

        while (true) {
            //非阻塞模式这个不会阻塞否则会阻塞
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                System.out.println("连接成功...");
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }

            Iterator<SocketChannel> iterable = channelList.iterator();
            while (iterable.hasNext()) {
                SocketChannel sc = iterable.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int len = sc.read(byteBuffer);
                if (len >0) {
                    System.out.println("接收到消息："+new String(byteBuffer.array()));
                } else if(len == -1){
                    iterable.remove();
                    System.out.println("客户端断开连接");
                }
            }
        }
    }
}
